package cn.itcast.oa.view.action;

import java.util.List;



import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.oa.base.BaseAction;
import cn.itcast.oa.domain.Department;

import cn.itcast.oa.util.DepartmentUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;


@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department> implements ModelDriven<Department>{
   
	
	private static final long serialVersionUID = 5582494379069721301L;


	
	private Long parentId;
	
	public Long getParentId() {
		return parentId;
	}

	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}
	

	/**列表 */
	public String list() throws Exception {
		List<Department> departmentlist=null;
		
		if(parentId == null){ //顶级部门列表
		departmentlist = departmentService.findTopList();
		}else{ //子部门列表
		departmentlist = departmentService.findChildren(parentId);
		
		Department parent= departmentService.getById(parentId);
		ActionContext.getContext().put("parent", parent);
		}
		ActionContext.getContext().put("departmentlist", departmentlist);
		
		
		
		return "list";
	}
	/**删除*/
	public String delete() throws Exception {
		departmentService.delete(model.getId());
		return "tolist";
	}
	/**添加页面*/
	public String addUI() throws Exception {
		//准备数据
		List<Department> topList=departmentService.findTopList();
		List<Department> departmentlist=DepartmentUtils.getAllDepartments(topList);
		
		ActionContext.getContext().put("departmentlist", departmentlist);
		return "saveUI";
	}
	/**添加 */
	public String add() throws Exception {
		//封装信息到对象中
		/*Department department = new Department();
		department.setName(model.getName());
		department.setDescription(model.getDescription());
		*/
		
		Department department = departmentService.getById(parentId);
		model.setParent(department);
		
		departmentService.save(model);
		return "tolist";
	}
	/**修改页面 */
	public String editUI() throws Exception {
		
		List<Department> topList=departmentService.findTopList();
		List<Department> departmentlist=DepartmentUtils.getAllDepartments(topList);
		
		ActionContext.getContext().put("departmentlist", departmentlist);
		
		//准备回显的数据
		Department department = departmentService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(department);
		if(department.getParent() != null){ 
			parentId= department.getParent().getId();
		}
		return "saveUI";
	}
	/**修改 */
	public String edit() throws Exception {
		Department department = departmentService.getById(model.getId());
		department.setName(model.getName());
		department.setDescription(model.getDescription());
		department.setParent(departmentService.getById(getParentId()));
		departmentService.update(department);
		return "tolist";
	}
}
